//
//  DDAddressBookUtils.m
//  PrivateCloud
//
//  Created by mars on 13-10-27.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDAddressBookUtils.h"
//#import "ABAddress"

@implementation DDAddressBookUtils
-(void)createVcard{
    ABAddressBookRef addressBookRef = nil;
    
    addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    
    ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted,CFErrorRef error){dispatch_semaphore_signal(sema);});
    
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    dispatch_release(sema);
    
    CFArrayRef* contacts = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    CFDataRef* vards = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(contacts);
    NSString *vcardString = [[NSString alloc]initWithData:(NSData*)vards encoding:NSUTF8StringEncoding];
    
//    vcardString = [vcardString stringByReplacingOccurrencesOfString:@"type=" withString:@""];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:@"local.vcf"];
    NSLog(@"path-------------%@",filePath);
    [vcardString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

-(NSString*)getLocalVcfPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:@"local.vcf"];
    return filePath;
}

-(NSString*)getLocalTempVcfPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:@"local_temp.vcf"];
    return filePath;
}

-(NSString*)getRemoteVcfPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:@"remote.vcf"];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:filePath]) {
        filePath = nil;
    }
    [fileManager release];
    return filePath;
}

-(void)createVcfFileWithCode:(int)code{
    NSString* fileName = nil;
    if(code == SERVER_CODE){
        fileName = @"remote.vcf";
    }
    else{
        fileName = @"local.vcf";
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        [fileManager removeItemAtPath:filePath error:nil];
    }
    [fileManager createFileAtPath:filePath contents:nil attributes:nil];
}


-(void)parseVcard{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *plistPath = [paths objectAtIndex:0];
    
    NSString *filePath = [plistPath stringByAppendingPathComponent:@"remote.vcf"];
    NSLog(@"remote--------%@",filePath);
    CFDataRef vCardData = (CFDataRef)[filePath dataUsingEncoding:NSUTF8StringEncoding];
//    ABAddressBookRef book = ABAddressBookCreate();
    ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, nil);
    ABRecordRef defaultSource = ABAddressBookCopyDefaultSource(book);
    CFArrayRef vCardPeople = ABPersonCreatePeopleInSourceWithVCardRepresentation(defaultSource, vCardData);
    for (CFIndex index = 0; index < CFArrayGetCount(vCardPeople); index++) {
        ABRecordRef person = CFArrayGetValueAtIndex(vCardPeople, index);
        ABAddressBookAddRecord(book, person, NULL);
        CFRelease(person);
    }
    CFRelease(vCardPeople);
    CFRelease(defaultSource);
    ABAddressBookSave(book, NULL);
    CFRelease(book);
}

-(void)createNewPersonWithAddressBook:(ABAddressBookRef)paramAddressBook andPerson:(DDContactInfo *)contactInfo
{
    ABRecordRef anthonyRobbins = [self newPersonWithAddressBook:paramAddressBook andPersonInfo:contactInfo];
    if (anthonyRobbins != NULL)
    {
        NSLog(@"Anthony Robbins' record is inserted into the Address Book."); CFRelease(anthonyRobbins);
    }
}

- (ABRecordRef)newPersonWithAddressBook:(ABAddressBookRef)paramAddressBook andPersonInfo:(DDContactInfo *)contactInfo
{
    // 通讯录中联系人对象
    ABRecordRef result = NULL;
    if (paramAddressBook == NULL)
    {
        NSLog(@"The address book is NULL.");
        return NULL;
    }
    
    if ([contactInfo.firstName length] == 0 && [contactInfo.lastName length] == 0)
    {
        NSLog(@"First name and last name are both empty.");
        return NULL;
    }
    
    result = ABPersonCreate();
    if (result == NULL){
        NSLog(@"Failed to create a new person.");
        return NULL;
    }
    BOOL couldSetFirstName = NO;
    BOOL couldSetLastName = NO;
    BOOL couldSetPhone = NO;
    BOOL couldSetEmail = NO;
    
    CFErrorRef setFirstNameError = NULL;
    CFErrorRef setLastNameError = NULL;
    CFErrorRef setEmailError = NULL;
 
    
    
    /* ------------------- 添加操作 -----------------------*/
    // 添加姓
    if (contactInfo.firstName!=nil) {
        couldSetFirstName = ABRecordSetValue(result, kABPersonFirstNameProperty, (CFTypeRef)contactInfo.firstName, &setFirstNameError);
    }
    
    // 添加名
    if(contactInfo.lastName != nil){
        couldSetLastName = ABRecordSetValue(result, kABPersonLastNameProperty, (CFTypeRef)contactInfo.lastName, &setLastNameError);
    }
    
    // 添加电
    NSArray *phoneKeys = [NSArray arrayWithObjects:@"mobile",@"home",@"work",nil];
    ABMultiValueRef mv =ABMultiValueCreateMutable(kABMultiStringPropertyType);
    for(int i=0;i<[contactInfo.phoneNums count];i++)
    {
        ABMultiValueIdentifier mi = ABMultiValueAddValueAndLabel(mv,(CFStringRef)[contactInfo.phoneNums objectAtIndex:i], (CFStringRef)[phoneKeys objectAtIndex:0], &mi);
    }
    
    for(int i=0;i<[contactInfo.homeNums count];i++)
    {
        ABMultiValueIdentifier mi = ABMultiValueAddValueAndLabel(mv,(CFStringRef)[contactInfo.homeNums objectAtIndex:i], (CFStringRef)[phoneKeys objectAtIndex:1], &mi);
    }
    
    for(int i=0;i<[contactInfo.workNums count];i++)
    {
        ABMultiValueIdentifier mi = ABMultiValueAddValueAndLabel(mv,(CFStringRef)[contactInfo.workNums objectAtIndex:i], (CFStringRef)[phoneKeys objectAtIndex:2], &mi);
    }
    ABRecordSetValue(result, kABPersonPhoneProperty, mv, NULL);
    // 添加Email
    if (contactInfo.email != nil) {
        ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        ABMultiValueAddValueAndLabel(multiEmail, contactInfo.email, kABWorkLabel, NULL);
        ABRecordSetValue(result, kABPersonEmailProperty, multiEmail, nil);
    }
    
    
    
    CFErrorRef couldAddPersonError = NULL;
    BOOL couldAddPerson = ABAddressBookAddRecord(paramAddressBook, result, &couldAddPersonError);
    if (couldAddPerson)
    {
        NSLog(@"Successfully added the person.");
    }
    else
    {
        NSLog(@"Failed to add the person.");
        CFRelease(result);
        result = NULL;
        return result;
    }
    if (ABAddressBookHasUnsavedChanges(paramAddressBook))
    {
        CFErrorRef couldSaveAddressBookError = NULL;
        BOOL couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);
        if (couldSaveAddressBook)
        {
            NSLog(@"Successfully saved the address book.");
        }
        else
        {
            NSLog(@"Failed to save the address book.");
        }
    }
    return result;
    
}
@end
